package com.sky.controller.user;

import com.sky.constant.RedisConstants;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "菜品浏览")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("查看菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        // 从缓存查询菜品
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(RedisConstants.CACHE_DISH_KEY + categoryId);

        // 查询到菜品直接返回
        if (list != null && list.size() > 0) {
            return Result.success(list);
        }

        Dish dish = Dish.builder()
                .status(StatusConstant.ENABLE)
                .categoryId(categoryId)
                .build();

        // 未查询到菜品则从数据库中查询菜品存入缓存后返回数据
        list = dishService.listWithFlavor(dish);
        redisTemplate.opsForValue().set(RedisConstants.CACHE_DISH_KEY + categoryId, list);
        return Result.success(list);
    }
}
